import time
from concurrent import futures

import requests
import re
import json
import socket
import urllib3

executor = futures.ThreadPoolExecutor(max_workers=20)


def allowed_gai_family():
    return socket.AF_INET


urllib3.util.connection.allowed_gai_family = allowed_gai_family
urllib3.util.connection.HAS_IPV6 = False


# 1.web登录腾讯视频
# 2.点击电影，F12打开找到网络,Ctrl+F搜索m38u，找到/proxyhttp的请求，复制请求体
# 3.找到/018_gzc类似请求，复制https请求路径，只需要复制/018_gzc之前的内容
# 4.拷贝这两个值到程序里面
# 5.还需把请求的cookie与user-Agent拷贝过来放到headers里面
# ps：程序中data与ts_url需保持一致，一定是同一个视频的，否则可能下载失败
def download(ts_url, name):
    headers = {
        'cookie': 'pgv_pvid=652762864; qq_domain_video_guid_verify=a7b69681e9bd0d9a; appuser=142FE1DCD2C72B33; RK=SQU0jQwY5b; ptcz=e5ce107617d2ed3235d3ae8143f83bbcb274769c702128c8be44b888f173a0b1; eas_sid=R1S6g9s1L317B35390d8N2R1I9; pac_uid=0_38b31b8669a0b; iip=0; lv_play_index=77; o_minduid=vmQJoH7QlYatE42UnNxhplD5gLHoFMKH; livelink_pvid=9815710720; pgv_info=ssid=s2901615364; _qpsvr_localtk=0.3878329917503347; _qimei_q36=; _qimei_h38=716d602a4aa8ec3d1e05137d02000003d17802; vversion_name=8.2.95; video_omgid=a7b69681e9bd0d9a; ad_session_id=4yewhmzniuekm; full_screen_cid_pause_times=1; full_screen_pause_times=1; _qimei_fingerprint=4a8ccd1c8b5ca7d53f80434ded506cdb; _qimei_uuid42=17a190e3135100a6cf2732885f0c197562a451581e; LPDFturn=619; LZCturn=734; LBSturn=817; LPPBturn=13; LZTturn=573; Lturn=502; LKBturn=558; v_qq_com_session_lapse_time=1698230378418; LPVLturn=304; LPLFturn=297; LPSJturn=831; LVINturn=70; LPHLSturn=683; LDERturn=532',
        'user-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
    }
    print(ts_url)
    start = time.time()
    ts_data = requests.get(ts_url, headers).content
    with open('./video/' + name, mode='wb') as f:
        f.write(ts_data)
    end = time.time()
    print(f'请求数据，耗时：{end - start}秒')


if __name__ == '__main__':
    headers = {
        'cookie': 'pgv_pvid=652762864; qq_domain_video_guid_verify=a7b69681e9bd0d9a; appuser=142FE1DCD2C72B33; RK=SQU0jQwY5b; ptcz=e5ce107617d2ed3235d3ae8143f83bbcb274769c702128c8be44b888f173a0b1; eas_sid=R1S6g9s1L317B35390d8N2R1I9; pac_uid=0_38b31b8669a0b; iip=0; lv_play_index=77; o_minduid=vmQJoH7QlYatE42UnNxhplD5gLHoFMKH; livelink_pvid=9815710720; pgv_info=ssid=s2901615364; _qpsvr_localtk=0.3878329917503347; _qimei_q36=; _qimei_h38=716d602a4aa8ec3d1e05137d02000003d17802; vversion_name=8.2.95; video_omgid=a7b69681e9bd0d9a; ad_session_id=4yewhmzniuekm; full_screen_cid_pause_times=1; full_screen_pause_times=1; _qimei_fingerprint=4a8ccd1c8b5ca7d53f80434ded506cdb; _qimei_uuid42=17a190e3135100a6cf2732885f0c197562a451581e; LPDFturn=619; LZCturn=734; LBSturn=817; LPPBturn=13; LZTturn=573; Lturn=502; LKBturn=558; v_qq_com_session_lapse_time=1698230378418; LPVLturn=304; LPLFturn=297; LPSJturn=831; LVINturn=70; LPHLSturn=683; LDERturn=532',
        'user-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
    }
    url = 'https://vd6.l.qq.com/proxyhttp'
    data = {
        "buid": "vinfoad",
        "vinfoparam": "charge=0&otype=ojson&defnpayver=3&spau=1&spaudio=0&spwm=1&sphls=2&host=v.qq.com&refer=https%3A%2F%2Fv.qq.com%2Fx%2Fcover%2Fmzc002007j7p5hn%2Fi0047g35s2e.html&ehost=https%3A%2F%2Fv.qq.com%2Fx%2Fcover%2Fmzc002007j7p5hn%2Fi0047g35s2e.html&sphttps=1&encryptVer=9.2&cKey=1ar0HXGI3IK1y81Orq2-LnCjnpb8Ocr0cPTc-sDVzEul_f4uOWcpWmJMR8Gx77I5OgQAgwcNw2rqCp7VHCeQghpmp7rG5tiHjLv_PnnatnPaZfOXktuBpd_Iz_Rs59Gdh13o_IMO5pZlFjOj-NmZhE-NjjawCzIdF66cdsFdzz5jk70UOmynTHDptaxqIemxrSlkg-M_BbDaBoWwiX7uSsBkDK_qlv9BvC71CgXl1BaviS_BqOyu7myQxXaZw0af2pySApuO_cBm7THy64l64PYvrkyjWSbCw9a-4kJ7EsQnKoWH0djjsMmNnLeut5kJP7AxmOExsITvfbCpmYgjx7BF2NniaucJNLfoL_EWkty6pUVceWUFqbILAyVSkxoyXr0vIf1IP_VjzMJopO1uwaenNOjb5crisBnIj8Aogp43xqHsN1WThvTw4y75s6FAJezp8USId5sGFggwom3Ln0VFoq2KtVhCSIC9GNusYoLZUuC0lJ24W5pqC2G0dDBCAxKmbHrJvIBrln5Curb4pambaAsIUqG20nh0BQUFBQVO-SlD&clip=4&guid=a7b69681e9bd0d9a&flowid=77a9295dfa293877cca259f00c2e4f04&platform=10201&sdtfrom=v1010&appVer=1.28.2&unid=&auth_from=&auth_ext=&vid=i0047g35s2e&defn=fhd&fhdswitch=0&dtype=3&spsrt=2&tm=1698303239&lang_code=0&logintoken=%7B%22access_token%22%3A%22DE56626FF0A5369EF3A3B2F32BA54267%22%2C%22appid%22%3A%22101483052%22%2C%22vusession%22%3A%22ldLfGsOBIjw-qqNh1XvQAQ.M%22%2C%22openid%22%3A%22E9E58E6049DF108B48BDD940297DF6DD%22%2C%22vuserid%22%3A%22168131411%22%2C%22video_guid%22%3A%22a7b69681e9bd0d9a%22%2C%22main_login%22%3A%22qq%22%7D&spvvpay=1&spadseg=3&spav1=15&hevclv=28&spsfrhdr=0&spvideo=0&spm3u8tag=67&spmasterm3u8=3&drm=40",
        "sspAdParam": "{\"ad_scene\":1,\"pre_ad_params\":{\"ad_scene\":1,\"user_type\":2,\"video\":{\"base\":{\"vid\":\"i0047g35s2e\",\"cid\":\"mzc002007j7p5hn\"},\"is_live\":false,\"type_id\":3,\"referer\":\"https://v.qq.com/channel/cartoon\",\"url\":\"https://v.qq.com/x/cover/mzc002007j7p5hn.html?j_vid=s3368kmiigq&j_cut_vid=m0044ufhrkv&j_is_win_vid=1&j_start=3.28\",\"flow_id\":\"77a9295dfa293877cca259f00c2e4f04\",\"refresh_id\":\"1ef9fceeaab8c8cde6778ac64dbcbbb1_1698302974\",\"fmt\":\"fhd\"},\"platform\":{\"guid\":\"a7b69681e9bd0d9a\",\"channel_id\":0,\"site\":\"web\",\"platform\":\"in\",\"from\":0,\"device\":\"pc\",\"play_platform\":10201,\"pv_tag\":\"www_baidu_com|x\",\"support_click_scan_integration\":true},\"player\":{\"version\":\"1.28.1\",\"plugin\":\"3.4.18\",\"switch\":1,\"play_type\":\"1\",\"img_type\":\"webp\"},\"token\":{\"type\":1,\"vuid\":168131411,\"vuser_session\":\"ldLfGsOBIjw-qqNh1XvQAQ.M\",\"app_id\":\"101483052\",\"open_id\":\"E9E58E6049DF108B48BDD940297DF6DD\",\"access_token\":\"DE56626FF0A5369EF3A3B2F32BA54267\"}}}",
        "adparam": "adType=preAd&vid=i0047g35s2e&sspKey=sljl"
    }

    response = requests.post(url=url, json=data, headers=headers)
    res_json = response.json()
    print(res_json)
    # 取结果中的vinfo字段
    vinfo = json.loads(res_json["vinfo"])
    # 提取m3u8相关的数据
    m3u8 = vinfo['vl']['vi'][0]['ul']['m3u8']
    ts_list = re.sub('#E.*', '', m3u8)
    ts_list = ts_list.split()
    names = []
    # ts_list = ts_list[:2]
    # print(ts_list)
    download_futures = []
    index = 0
    for ts in ts_list:
        # 非vip下载地址
        # ts_url = 'https://apd-vlive.apdcdn.tc.qq.com/moviets.tc.qq.com/AxmW9YLh_DJDv5H4TqDCpxXqWMCczxvytfIPB5kLB2AY/B_XztNc2Ue3HgxgyyNa2AR9ST8sqpvs6S8Gp80I5XuAysIwRI0crSo5R9XAd9FxN2d/svp_50112/Gj-bauiwm9-aljek0l7_Wd4bodOOtjy-_Fm7OFGo09QCWJMofV76brUzXms8AaOt_UwFrNFfdX6MFVcAZi71TTweu8sl4Va1xfJnbPjKxnZ8X4VgDSSON2voRZ3iNiutlCGUQUTeoeXpfOnS0HGmi-idEyE7X8NOF6NhzO-5pcNeuahXdFtBnxVnmmqApJhTt1_O-thlpszCDyKEG3xZWcneB4BZgNhz7TQKCm9cWxmK_hw1KK2qsw/' + ts
        # vip下载地址
        index += 1
        indexIn = index
        indexStr = str(indexIn) + ".ts"
        names.append(indexStr)
        ts_url = 'https://apd-vlive.apdcdn.tc.qq.com/moviets.tc.qq.com/A5kp3Yp9x3MIVLOO6ZXFlbNiGHx6itXwknsYR2wkoZ8I/B_XztNc2Ue3HgxgyyNa2AR9dFzGbRvS2lMSHQtwJfwzf5jfUfG-XRPQETNJn4jWWZY/svp_50112/c2zxlGRMCldTBf3DM56G_CYgqDHsikZT7hO4xCRjNeWFWd7X0c92Sb2yCR_2BtlUjNDGVaxOIDoaQWbAZVaYlIwQzwijKTSvXaNg7hbr3yhCzuJh9DER4upZQlKfmHzVe38syyTzKECUnlpZaRuJ1k91vR_POAs9yhnGFUFIGptpQxsIaBZdaUNHiPPWZUXGHXXFhtVHE0yM5zLZFiRZO2cLJ2hV37KB9-NIpGHnIADi1ej_brmTkw/' + ts
        # https://apd-vlive.apdcdn.tc.qq.com/vipts.tc.qq.com/ADIs8KRhgwqMoh7LOe_1Q-F1p-IGQA61ged_NVDK0Ljw/B_tRCdt2L6hl1ezG-aht1_pwX5lMxY-yr38q8QBvPy2SH3TjKi7hD4hPCsaqVncwV6/svp_50112/e5Whd7fYRggV1QoCr6RuiNh4HYHKS4SIKwcbnnEpf-jChKT5Q0QRPXlkw5b8lUiPW6-LOqIgeSczmjivhDKpuPRJ1YiqTN2hLbTttXvyGgnwcWKE_ov9BK9QTE7fNa6ZmCDaPWjOkm69F_NMCHxeGnEVYKQZ6821JvY1SkygRTWVVK0KKJTopdlT3X2FMbpMvP1WqCebV4HeiAK_cMEvPQQDJolQk2V0ZY9DcLKwdMzYzzleaZoOhw/04_gzc_1000102_0b53ouaamaaa6madbtbj4vs4a5odazzqaasa.f322064.1.ts?index=4&start=47520&end=58960&brs=8028352&bre=10132071&ver=4&token=c92ba5089f491d69d97476b06133c415https://apd-vlive.apdcdn.tc.qq.com/vipts.tc.qq.com/ADIs8KRhgwqMoh7LOe_1Q-F1p-IGQA61ged_NVDK0Ljw/B_tRCdt2L6hl1ezG-aht1_pwX5lMxY-yr38q8QBvPy2SH3TjKi7hD4hPCsaqVncwV6/svp_50112/e5Whd7fYRggV1QoCr6RuiNh4HYHKS4SIKwcbnnEpf-jChKT5Q0QRPXlkw5b8lUiPW6-LOqIgeSczmjivhDKpuPRJ1YiqTN2hLbTttXvyGgnwcWKE_ov9BK9QTE7fNa6ZmCDaPWjOkm69F_NMCHxeGnEVYKQZ6821JvY1SkygRTWVVK0KKJTopdlT3X2FMbpMvP1WqCebV4HeiAK_cMEvPQQDJolQk2V0ZY9DcLKwdMzYzzleaZoOhw/05_gzc_1000102_0b53ouaamaaa6madbtbj4vs4a5odazzqaasa.f322064.1.ts?index=5&start=58960&end=70280&brs=10132072&bre=14660051&ver=4&token=8c0e4fadbb1227a65a854c4fe924524d
        # print(ts_url)
        download_futures.append(executor.submit(download, ts_url, indexStr))

        # ts_data = requests.get(ts_url).content
        # with open('斗罗.mp4', mode='ab') as f:
        #     f.write(ts_data)
    futures.wait(download_futures)
    # if futures.as_completed(download_futures):
    with open('./video/test.mp4', mode='ab') as f:
        for name in names:
            with open('./video/' + name, mode='rb') as vi:
                vibytes = vi.read()
                f.write(vibytes)
    # print(requests.get("https://www.baidu.com?123"))
